package com.boomsecret.unsafe;

import sun.misc.Unsafe;

import java.lang.reflect.Field;
import java.util.Arrays;

/**
 * @author wangjinliang on 2019/1/18.
 */
public class UnsafeObjectDemo {
    private static Unsafe UNSAFE;

    static {
        try {
            Field f = Unsafe.class.getDeclaredField("theUnsafe");
            f.setAccessible(true);
            UNSAFE = (Unsafe) f.get(null);
        } catch (Exception e) {
            throw new RuntimeException("init error.");
        }
    }

    public static void main(String[] args) throws Exception {
        Field countField = UnsafeUser.class.getDeclaredField("count");
        long countOffset = UNSAFE.objectFieldOffset(countField);

        UnsafeUser unsafeUser = (UnsafeUser) UNSAFE.allocateInstance(UnsafeUser.class);
        System.out.println(UNSAFE.getInt(unsafeUser, countOffset));
        UNSAFE.putInt(unsafeUser, countOffset, 100);

        System.out.println(UNSAFE.getInt(unsafeUser, countOffset));
        System.out.println(unsafeUser);
        System.out.println("-----------------");
    }

    public static class UnsafeUser {
        protected int count;
        protected String[] array = {"aa", "bb", "cc"};

        @Override
        public String toString() {
            return "UnsafeUser{" +
                    "count=" + count +
                    ", array=" + Arrays.toString(array) +
                    '}';
        }
    }
}
